package com.aabte.nettyleran.io.bio;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * 伪异步IO Server
 *
 * @author Daniel
 * @version 1.0
 * @date 2020/3/11
 */
public class GuiseTimeServer {

    public static void main(String[] args) {

        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        ServerSocket server = null;
        try {
            server = new ServerSocket(port);
            System.out.println("The time server is start in port: " + port);
            Socket socket = null;

            TimeServerHandlerExecutePool singleExecutor = new TimeServerHandlerExecutePool(50, 10000);

            while (true) {
                socket = server.accept();
                new Thread(new TimeServerHandler(socket)).start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (server != null) {
                System.out.println("The time server close.");
                try {
                    server.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                server = null;
            }
        }

    }

    private static class TimeServerHandlerExecutePool {

        private ExecutorService executor;

        public TimeServerHandlerExecutePool(int maxPoolSize, int queueSize) {

            ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("time-server-handle-%d").build();

            this.executor = new ThreadPoolExecutor(Runtime.getRuntime()
                    .availableProcessors(), maxPoolSize, 120L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueSize), threadFactory);
        }

        public void execute(Runnable task) {
            executor.execute(task);
        }
    }
}
